#include <iostream>
#include <pthread.h>
#include <unistd.h>

//全局锁
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
//全局条件变量
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void* handler(void* arg)
{
    while(true)
    {
        //申请锁资源
        pthread_mutex_lock(&mutex);
        //等待条件变量就绪
        pthread_cond_wait(&cond, &mutex);
        //临界区
        std::cout << pthread_self() << "-thread entry critical section" << std::endl;
        //释放锁资源
        pthread_mutex_unlock(&mutex);
    }
}

int main()
{
    //创建线程
    for(int i = 0; i < 5; i++)
    {
        pthread_t tid;
        pthread_create(&tid, nullptr, handler, nullptr);
        //线程分离--无需等待
        pthread_detach(tid);
    }

    //反复让条件变量就绪，唤醒一个线程
    while(true)
    {
        pthread_cond_signal(&cond);
        sleep(1);
    }

    return 0;
}